const { PrismaClient } = require('@prisma/client');
const bcrypt = require('bcryptjs');

const prisma = new PrismaClient();

async function resetAdminPassword() {
  try {
    console.log('开始重置admin用户密码...');
    
    // 检查admin用户是否存在
    const admin = await prisma.user.findUnique({
      where: { username: 'admin' }
    });
    
    if (!admin) {
      console.log('找不到admin用户，尝试创建...');
      // 获取admin角色
      const adminRole = await prisma.role.findFirst({
        where: { name: 'admin' }
      });
      
      if (!adminRole) {
        console.error('找不到admin角色，请先确保角色数据已初始化');
        return;
      }
      
      // 创建新的admin用户
      const hashedPassword = await bcrypt.hash('123456', 10);
      await prisma.user.create({
        data: {
          username: 'admin',
          password: hashedPassword,
          name: '管理员',
          roleId: adminRole.id,
          status: true,
          updatedAt: new Date()
        }
      });
      console.log('已创建新的admin用户，密码设为: 123456');
    } else {
      // 更新现有admin用户的密码
      const hashedPassword = await bcrypt.hash('123456', 10);
      await prisma.user.update({
        where: { id: admin.id },
        data: { password: hashedPassword }
      });
      console.log('已重置admin用户密码为: 123456');
    }
  } catch (error) {
    console.error('重置密码时出错:', error);
  } finally {
    await prisma.$disconnect();
  }
}

resetAdminPassword(); 